import re
from typing import List, Dict, Any
from src.domain.emailqa import EmailQA
from src.domain.repository import EmailQARepository
from src.domain.sop import SOP
from src.domain.sop_repository import SOPRepository


class EmailQAService:
    def __init__(self, repository: EmailQARepository):
        self.repository = repository
    
    def get_email_qa_by_ids(self, ids: List[int]) -> List[Dict[str, Any]]:
        email_qa_list = self.repository.find_by_ids(ids)
        
        result = []
        for email_qa in email_qa_list:
            email_dict = {
                'id': email_qa.id,
                'system_conversation_id': email_qa.system_conversation_id,
                'q_body': email_qa.q_body,
                'q_subject': email_qa.q_subject,
                'q_real_question': email_qa.q_real_question,
                'q_question_subject': email_qa.q_question_subject,
                'q_attachment_content': email_qa.q_attachment_content,
                'customer_service_answer': email_qa.customer_service_answer,
                'context_email_conversation_history_summary': email_qa.context_email_conversation_history_summary,
                'context_order_info': email_qa.context_order_info,
                'email_type': email_qa.email_type.value
            }
            result.append(email_dict)
        
        total_chars = sum(len(str(item)) for item in result)
        if total_chars > 80000:
            raise ValueError(f"Total data size {total_chars} exceeds limit of 80000 characters")
        
        return result
    
    def create_email_qa(self, email_qa_data: Dict[str, Any]) -> Dict[str, Any]:
        from src.domain.emailqa import EmailType
        
        email_type = EmailType.PLATFORM if email_qa_data.get('customer_service_answer', '').startswith('Hi TEAM,') else EmailType.CUSTOMER
        
        email_qa = EmailQA(
            id=0,
            system_conversation_id=email_qa_data.get('system_conversation_id', ''),
            q_body=email_qa_data.get('q_body', ''),
            q_subject=email_qa_data.get('q_subject', ''),
            q_real_question=email_qa_data.get('q_real_question', ''),
            q_question_subject=email_qa_data.get('q_question_subject', ''),
            q_attachment_content=email_qa_data.get('q_attachment_content', ''),
            customer_service_answer=email_qa_data.get('customer_service_answer', ''),
            context_email_conversation_history_summary=email_qa_data.get('context_email_conversation_history_summary', ''),
            context_order_info=email_qa_data.get('context_order_info', '{}'),
            email_type=email_type
        )
        
        new_id = self.repository.create(email_qa)
        
        return {
            'id': new_id,
            'system_conversation_id': email_qa.system_conversation_id,
            'q_body': email_qa.q_body,
            'q_subject': email_qa.q_subject,
            'q_real_question': email_qa.q_real_question,
            'q_question_subject': email_qa.q_question_subject,
            'q_attachment_content': email_qa.q_attachment_content,
            'customer_service_answer': email_qa.customer_service_answer,
            'context_email_conversation_history_summary': email_qa.context_email_conversation_history_summary,
            'context_order_info': email_qa.context_order_info,
            'email_type': email_qa.email_type.value
        }


class TaskIdParser:
    @staticmethod
    def parse_task_ids(content_list: List[str]) -> List[int]:
        task_ids = []
        pattern = r'task_id=(\d+)'
        
        for content in content_list:
            matches = re.findall(pattern, content)
            for match in matches:
                try:
                    task_id = int(match)
                    task_ids.append(task_id)
                except ValueError:
                    continue
        
        return task_ids


class SOPService:
    def __init__(self, repository: SOPRepository):
        self.repository = repository
    
    def get_sop_by_ids(self, sop_ids: List[int]) -> List[Dict[str, Any]]:
        """Get SOP data by IDs and return as list of dictionaries."""
        sop_list = self.repository.find_by_ids(sop_ids)
        
        result = []
        for sop in sop_list:
            sop_dict = {
                'id': sop.id,
                'subject': sop.subject,
                'sop': sop.sop,
                'created_at': sop.created_at.isoformat(),
                'created_by': sop.created_by
            }
            result.append(sop_dict)
        
        return result


class SOPIdParser:
    @staticmethod
    def parse_sop_ids(content_list: List[str]) -> List[int]:
        """Parse SOP IDs from content list using regex pattern."""
        sop_ids = []
        pattern = r'id=(\d+)'
        
        for content in content_list:
            matches = re.findall(pattern, content)
            for match in matches:
                try:
                    sop_id = int(match)
                    sop_ids.append(sop_id)
                except ValueError:
                    continue
        
        return sop_ids